package com.systop.asset.controller;

import com.systop.asset.entity.LoginBody;
import com.systop.asset.entity.RestResponse;
import com.systop.asset.entity.vo.LoginUser;
import com.systop.asset.enums.HttpCodeEnum;
import com.systop.asset.service.LoginService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.webauthn.authentication.WebAuthnAuthentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;



@RestController
@RequestMapping("/system")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private SecurityContextRepository securityContextRepository;


    private final AuthenticationManager authenticationManager;

    public LoginController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public RestResponse login(HttpServletRequest request,
                              HttpServletResponse response, @RequestBody LoginBody loginBody)
    {
        if (loginBody.getUsername() == null || "".equals(loginBody.getUsername())) {

            return RestResponse.failure(HttpCodeEnum.BODY_NAME_NOT_NULL);
        }
        if (loginBody.getPassword() == null || "".equals(loginBody.getPassword())) {

            return RestResponse.failure(HttpCodeEnum.PASSWORD_NOT_NULL);
        }


        long userid;
        if ((userid = loginService.login(loginBody)) == -1) {
            return RestResponse.failure(HttpCodeEnum.PHONE_OR_PASSWORD_ERROR);
        }

        // 创建新权限集合
        List<GrantedAuthority> updatedAuthorities = new ArrayList<>();
        updatedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        Authentication authentication = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), userid, updatedAuthorities);
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        // 保存到SecurityContextHolder和Session
        SecurityContextHolder.setContext(context);
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(loginBody.getUsername());
        loginUser.setId(userid);
        loginUser.setSessionId(request.getSession().getId());

        securityContextRepository.saveContext(context, request, response);
        return RestResponse.success(loginUser);

    }


    @GetMapping("/current-user")
    public String currentUser(HttpServletRequest request) {
        System.out.println("当前用户: " + SecurityContextHolder.getContext().getAuthentication());
        System.out.println("当前用户id: " + SecurityContextHolder.getContext().getAuthentication().getCredentials());
        System.out.println("当前用户sessionId: " + request.getSession().getId());
        return "当前用户: " + SecurityContextHolder.getContext().getAuthentication();
    }
    @PostMapping("/logout")
    public RestResponse logout(HttpServletRequest request, HttpServletResponse response) {
        // 1. 获取当前 SecurityContext 并清除认证信息
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);

        // 2. 清除 session
        request.getSession().invalidate();
        // 3. 删除 JSESSIONID Cookie
        Cookie cookie = new Cookie("JSESSIONID", null);
        cookie.setPath("/");                  // 匹配路径
        cookie.setMaxAge(0);                  // 立即过期
        cookie.setHttpOnly(true);             // 匹配原始设置
        cookie.setSecure(request.isSecure()); // 根据当前请求是否使用 HTTPS
        response.addCookie(cookie);           // 添加到响应头

        // 4. 使用了 SecurityContextRepository，也可以调用 saveContext 来持久化清理后的上下文
        securityContextRepository.saveContext(context, request, response);

        return RestResponse.success("退出成功");
    }
}
